package com.ikangtai.shecare.stickycalendar.http;

import android.content.Context;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.al.Algorithm;
import com.ikangtai.shecare.common.al.CycleUnitDS;
import com.ikangtai.shecare.common.al.DayUnitDSInput;
import com.ikangtai.shecare.common.al.DayUnitDSOutput;
import com.ikangtai.shecare.common.al.UserUnitDS;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.db.sync.SyncALData1;
import com.ikangtai.shecare.common.db.sync.SyncRecordInfo1;
import com.ikangtai.shecare.common.eventBusMsg.AlgoUpdateMsg;
import com.ikangtai.shecare.common.eventBusMsg.TemperUploadMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncALDataMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncALDataMsg1;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncRecordInfoMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncRecordInfoMsg1;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.InternetUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.record.bean.UserRecordData;
import com.ikangtai.shecare.stickycalendar.http.util.MensesMsg;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by ikangtai on 2016/8/24.
 */
public class MensesHttp {

    private static final OkHttpClient mOkHttpClient = App.getOKHttpClient();
    private Context context;
    private static DBManager dbManager;

    private String dateRecord; // 具体某天的时间
    private int mensesHintValue;  //显示姨妈来了为1， 显示姨妈走了为0
    private int referMensesChoiceValue;
    public static int mensesBlood, mensesDysmenorrhea, mensesColor, mensesStatusBlock, mensesStatusOdour, mensesStatusDrossy, mensesFlow; // 这些变量的值应在进入该类时对其赋值
    public static int mensesInfo = 0;
    public UserRecordData userRecordData = new UserRecordData();
    private Algorithm algorithm;
    private boolean isAlgorithmUsed = false;
    private JSONArray jsonArrayCycleDatas, jsonArrayUserDatas;
    private JSONObject jsonObjectUserData;
    private List<MensesMsg> mensesMsgList;

    public MensesHttp(Context context,List<MensesMsg> mensesMsgList) {
        this.context = context;
        this.mensesMsgList = mensesMsgList;
        dbManager = new DBManager(context);
        EventBus.getDefault().register(this);
        algorithm = new Algorithm(context);

        mensesHintValue = mensesMsgList.get(0).getMensesHintValue();
        referMensesChoiceValue = mensesMsgList.get(0).getReferMensesChoiceValue();
        mensesBlood = mensesMsgList.get(0).getMensesBlood();
        dateRecord = mensesMsgList.get(0).getDateRecord(); // 时间需要传进来

        userRecordData = dbManager.getSelectedDayRecordData(App.userName, dateRecord);
        userRecordData.setId(userRecordData.getId());

        AppLog.i("wzz----调用开始");
    }

    public void saveSelectedDayRecord() {

        long currentTime = DateUtil.getStringToDate(DateUtil.getCurrentDay() + " 00:00:00");
        long recordDateZeroTime = DateUtil.getStringToDate(dateRecord + " 00:00:00");

        AppLog.i("wzz----currentTime---"+currentTime);
        AppLog.i("wzz----recordDateZeroTime---"+recordDateZeroTime);

        if (recordDateZeroTime > currentTime) {
            Toast.makeText(context, R.string.edit_record_information_future, Toast.LENGTH_SHORT).show();
            return;
        }
        CycleUnitDS[] cycleUnitDS = dbManager.getAllMensesConfirmStartHaveALCycleOutput(App.userName);

        AppLog.i("wzz----cycleUnitDS---"+cycleUnitDS);

        if(mensesHintValue == 1 && referMensesChoiceValue == 1 && mensesBlood == 0 && cycleUnitDS.length == 1 && cycleUnitDS[0].menstruationStartConfirm == DateUtil.getStringToDate(dateRecord + " 12:00:00")){
//            showInputLastPeriodDateDialog(); // 弹出输入最后一次月经时间的对话框（如果用户要将其最后一个月经标记删除的话）
        }else{
//            getRecordInfo(); // 获取添加后的记录数据
////            if (!isRecordDataChanged()) {
////                Toast.makeText(getActivity(), R.string.record_information_no_change, Toast.LENGTH_SHORT).show();
////                return;
////            }
////
////            showProgressDialog();
////
////            saveLHAndHCGAndBU();
//            syncAndUploadRecordDatas();

            uploadRecordInfo();
        }
    }

    /**
     * 获得月经的相关数据
     */
    private void getRecordInfo() {
        AppLog.i("wzz-------userRecordData.getId()------" + userRecordData.getId());
        if ("".equals(userRecordData.getId()) || null == userRecordData.getId()) {
            userRecordData.setId(UUID.randomUUID().toString());
        }
        userRecordData.setUserName(App.userName);

        if (0 == userRecordData.getRecordDate())
            userRecordData.setRecordDate(DateUtil.getStringToDate(dateRecord + " 12:00:00"));
        else userRecordData.setRecordEditDate(new Date().getTime() / 1000);

        mensesInfo = (mensesBlood) | (mensesDysmenorrhea << 5) | (mensesFlow << 2) | (mensesColor << 8) | (mensesStatusBlock << 11) | (mensesStatusOdour << 12) | (mensesStatusDrossy << 13);
        AppLog.i("mensesInfo:" + Integer.toBinaryString(mensesInfo));
        AppLog.i("wzz-------mensesInfo------" + mensesInfo);
        userRecordData.setMensesInfo(mensesInfo);
    }

    /**
     * 同步记录数据
     */
    private void syncAndUploadRecordDatas() {
        if (InternetUtil.hasInternet()) {
            AppLog.i("wzz-------有网络");
            SyncRecordInfoMsg1 syncRecordInfoMsg = new SyncRecordInfoMsg1();
            syncRecordInfoMsg.setSyncInActivity(SyncALDataMsg.SYNC_IN_RECORDFRAGMENT);
            SyncRecordInfo1 syncRecordInfo = new SyncRecordInfo1(context, syncRecordInfoMsg);
            AppLog.e("SyncRecordInfoWithNetwork");
            syncRecordInfo.syncRecordInfoWithNetwork();
        } else {
            uploadRecordInfo();
        }
    }

    @Subcriber
    private void syncRecordDataInRecordActivity1(SyncRecordInfoMsg1 syncRecordInfoMsg) {
        AppLog.i("wzz---进----syncRecordDataInRecordActivity");
        if (syncRecordInfoMsg.getSyncInActivity().equals(SyncRecordInfoMsg.SYNC_RECORD_IN_RECORDFRAGMENT)) {
            uploadRecordInfo();
        }
    }

    private void uploadRecordInfo(){
        getRecordInfo();

        OKHttpUtil okHttpClient = new OKHttpUtil(context);

        String appendUrl = "sync/replacePeriodMsg.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("id", userRecordData.getId());
            okHttpClient.add("recordDate", ""+DateUtil.getDateTimeStr2bit(userRecordData.getRecordDate()));
            okHttpClient.add("menstruationProperty", userRecordData.getMensesInfo());
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {
                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                    saveRecordData(0);
                    syncAndUpdateCycleDatas(0);
                }

                @Override
                public void onResponse(Response response) throws IOException {

                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        AppLog.i("wzz------重写----返回值----"+respCode);

                        if (App.HTTP_RESP_OK == respCode) {
                            saveRecordData(1);
                            syncAndUpdateCycleDatas(1);

                        } else if (App.HTTP_RESP_TOKEN_TIME_OUT == respCode) {
                            OKHttpUtil.setNewToken();
                            uploadRecordInfo();
                        } else {
                            saveRecordData(0);
                            syncAndUpdateCycleDatas(0);
                        }
                    } catch (JSONException e) {
                        AppLog.i("save nickName onResponse failed!");
                        e.printStackTrace();
                        saveRecordData(0);
                        syncAndUpdateCycleDatas(0);
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("save nickName JSONException!");
            e.printStackTrace();
            saveRecordData(0);
            syncAndUpdateCycleDatas(0);
        }

    }

    private void uploadRecordInfo1() {

        getRecordInfo();
//        if (selectedDayTemper.size() > 0 || deleteDayTemper.size() > 0) {
//            UserTemperatureInfo[] userTemperatureInfos = new UserTemperatureInfo[selectedDayTemper.size() + deleteDayTemper.size()];
//            if (selectedDayTemper.size() > 0) {
//                for (int i = 0; i < selectedDayTemper.size(); i++) {
//                    userTemperatureInfos[i] = selectedDayTemper.get(i);
//                }
//                if (deleteDayTemper.size() > 0) {
//                    for (int i = selectedDayTemper.size(); i < (selectedDayTemper.size() + deleteDayTemper.size()); i++) {
//                        userTemperatureInfos[i] = deleteDayTemper.get(i - selectedDayTemper.size());
//                    }
//                }
//                userRecordData.setUserTemperatureInfos(userTemperatureInfos);
//
//            } else {
//                for (int i = 0; i < deleteDayTemper.size(); i++) {
//                    userTemperatureInfos[i] = deleteDayTemper.get(i);
//                }
//
//                userRecordData.setUserTemperatureInfos(userTemperatureInfos);
//            }
//        }

        JSONArray jsonArray = new JSONArray();
        jsonArray.put(userRecordData.getUserRecordDataInfoJson());
        AppLog.i("authToken = " + App.authToken + ", jsonArray = " + jsonArray.toString());
        AppLog.i("wzz---------authToken = " + App.authToken + ", jsonArray = " + jsonArray.toString());
        OKHttpUtil okHttpClient = new OKHttpUtil(context);
        String appendUrl = "sync/addSignsRecords.json";
        try {

            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("records", jsonArray);

            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    saveRecordData(0);
//                    saveTemperatureRecord(0);
                    syncAndUpdateCycleDatas(0);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {

                    try {
                        String str = response.body().string();
                        AppLog.i("addSignsRecords response:" + str);
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");
                        AppLog.i("wzz---------respCode----------"+respCode);
                        if (App.HTTP_RESP_OK == respCode) {
                            AppLog.i("addSignsRecords onResponse success!");
                            saveRecordData(1);
//                            saveTemperatureRecord(1);
                            syncAndUpdateCycleDatas(1);
                            AppLog.i("wzz---------syncAndUpdateCycleDatas(1)");
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                            temperUploadMsg.setUpdateCode(App.HTTP_RESP_TOKEN_TIME_OUT);
                            EventBus.getDefault().post(temperUploadMsg);
                        } else {
                            AppLog.i("addSignsRecords onResponse failed! respCode = " + respCode);
                            saveRecordData(0);
//                            saveTemperatureRecord(0);
                            syncAndUpdateCycleDatas(0);
                        }
                    } catch (JSONException e) {
                        saveRecordData(0);
//                        saveTemperatureRecord(0);
                        syncAndUpdateCycleDatas(0);
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            saveRecordData(0);
//            saveTemperatureRecord(0);
            syncAndUpdateCycleDatas(0);
            AppLog.i("UploadCycleData JSONException!");
            e.printStackTrace();
        }
    }

    private void saveRecordData(int isSynced) {
        userRecordData.setIsSynced(isSynced);
        dbManager.saveRecordData(userRecordData);

//        if (userRecordData.getMensesInfo() == 0 && originRecordData.getMensesInfo() != 0) {
//            if (null != dbManager.getLastMensesRecordData(App.userName)) {
//                App.memory_preference_lastPeriodDate = DateUtil.getDateStr2bit(dbManager.getLastMensesRecordData(App.userName).getRecordDate());
//                dbManager.updateUserPreference(App.userName, "lastPeriodDate", App.memory_preference_lastPeriodDate);
//            }
//        } else if (userRecordData.getMensesInfo() != 0) {
//            if (null != dbManager.getLastMensesRecordData(App.userName)) {
//                App.memory_preference_lastPeriodDate = DateUtil.getDateStr2bit(dbManager.getLastMensesRecordData(App.userName).getRecordDate());
//                dbManager.updateUserPreference(App.userName, "lastPeriodDate", App.memory_preference_lastPeriodDate);
//            }
//        }
    }

    /**
     * 同步算法数据
     * @param isSynced
     */
    private void syncAndUpdateCycleDatas(int isSynced) {
        if (InternetUtil.hasInternet()) {
            SyncALDataMsg1 syncALDataMsg = new SyncALDataMsg1();
            syncALDataMsg.setSyncInActivity(SyncALDataMsg.SYNC_IN_RECORDFRAGMENT);

            SyncALData1 syncALData = new SyncALData1(context, syncALDataMsg);
            AppLog.e("SyncALDataWithNetwork");
            syncALData.SyncALDataWithNetwork();
        } else {
            updateCycleDatas(isSynced);
        }
    }

    @Subcriber
    private void syncRecordChangeALData(SyncALDataMsg1 syncALDataMsg) {
        if (syncALDataMsg.getSyncInActivity().equals(SyncALDataMsg.SYNC_IN_RECORDFRAGMENT)) {
            if (algorithm != null) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        updateCycleDatas(1);
                    }
                }).start();
            }
        }
    }

    /**
     * 姨妈来了调用的算法
     *
     *wzz 算法
     *
     * @param isSynced
     */
    private void updateCycleDatas(int isSynced) {

        AppLog.i("wzz-----进算法啦~~");

//        long recordDaySeconds = DateUtil.getStringToDate(dateRecord + " 00:00:00");
//        AppLog.e("start algorithm in recordFragment");
//        if(mensesHintValue == 1 && referMensesChoiceValue == 0 && mensesBlood == 1){//1姨妈来了/0走了   初始状态下的选择按钮（1选择开关打开/0关闭）      点击后的状态值
//            AppLog.i("algorithm Menses inputStart");
//            int result = algorithm.executeAL(2, algorithm.getMensesDayInput(recordDaySeconds, 2), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
//            if(result == 234) g1Tog2Algorithm();
//            isAlgorithmUsed = true;
//        }
//        if(mensesHintValue == 0 && referMensesChoiceValue == 0 && mensesBlood == 1){
//            AppLog.i("algorithm Menses inputEnd");
//            int result = algorithm.executeAL(3, algorithm.getMensesDayInput(recordDaySeconds, 3), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
//            if(result == 234) g1Tog2Algorithm();
//            isAlgorithmUsed = true;
//        }
//        if(mensesHintValue == 1 && referMensesChoiceValue == 1 && mensesBlood == 0){
//            AppLog.i("algorithm Menses deleteStart");
//            int result = algorithm.executeAL(4, algorithm.getMensesDayInput(recordDaySeconds, 4), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
//            if(result == 234) g1Tog2Algorithm();
//            long currentDayCycleUnitDSMensesStartConfirm = dbManager.getSelectedDayCycleUnitDSMensesStartConfirm(App.userName, new Date().getTime() / 1000);
//            AppLog.e("currentDayCycleUnitDSMensesStartConfirm:" + currentDayCycleUnitDSMensesStartConfirm);
//            long periodAchieveConfirm = dbManager.getSelectedDayALDayUnitDSOutput(App.userName, currentDayCycleUnitDSMensesStartConfirm).periodAchieveConfirm;
//            AppLog.e("periodAchieveConfirm:" + periodAchieveConfirm);
//            if(periodAchieveConfirm == 0){
//                changeForecastStart();
//            }
//            isAlgorithmUsed = true;
//        }
//        if(mensesHintValue == 0 && referMensesChoiceValue == 1 && mensesBlood == 0){
//            AppLog.i("algorithm Menses deleteEnd");
//            int result = algorithm.executeAL(5, algorithm.getMensesDayInput(recordDaySeconds, 5), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
//            if(result == 234) g1Tog2Algorithm();
//            isAlgorithmUsed = true;
//        }

        long recordDaySeconds = DateUtil.getStringToDate(dateRecord + " 00:00:00");
        AppLog.e("start algorithm in recordFragment");
        if(mensesHintValue == 1 && referMensesChoiceValue == 0 && mensesBlood == 1){//1姨妈来了/0走了   初始状态下的选择按钮（1选择开关打开/0关闭）      点击后的状态值
            AppLog.i("algorithm Menses inputStart");
            int result = algorithm.executeAL(2, algorithm.getMensesDayInput(recordDaySeconds, 2), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
            if(result == 234) g1Tog2Algorithm();
            long currentDayCycleUnitDSMensesStartConfirm = dbManager.getSelectedDayCycleUnitDSMensesStartConfirm(App.userName, new Date().getTime() / 1000);
            AppLog.e("currentDayCycleUnitDSMensesStartConfirm:" + currentDayCycleUnitDSMensesStartConfirm);
            long periodAchieveConfirm = dbManager.getSelectedDayALDayUnitDSOutput(App.userName, currentDayCycleUnitDSMensesStartConfirm).periodAchieveConfirm;
            AppLog.e("periodAchieveConfirm:" + periodAchieveConfirm);
            if(periodAchieveConfirm == 0){
                changeForecastStart();
            }
            isAlgorithmUsed = true;
        }
        if(mensesHintValue == 0 && referMensesChoiceValue == 0 && mensesBlood == 1){
            AppLog.i("algorithm Menses inputEnd");
            int result = algorithm.executeAL(3, algorithm.getMensesDayInput(recordDaySeconds, 3), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
            if(result == 234) g1Tog2Algorithm();
            isAlgorithmUsed = true;
        }
        if(mensesHintValue == 1 && referMensesChoiceValue == 1 && mensesBlood == 0){
            AppLog.i("algorithm Menses deleteStart");
            int result = algorithm.executeAL(4, algorithm.getMensesDayInput(recordDaySeconds, 4), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
            if(result == 234) g1Tog2Algorithm();
            long currentDayCycleUnitDSMensesStartConfirm = dbManager.getSelectedDayCycleUnitDSMensesStartConfirm(App.userName, new Date().getTime() / 1000);
            AppLog.e("currentDayCycleUnitDSMensesStartConfirm:" + currentDayCycleUnitDSMensesStartConfirm);
            long periodAchieveConfirm = dbManager.getSelectedDayALDayUnitDSOutput(App.userName, currentDayCycleUnitDSMensesStartConfirm).periodAchieveConfirm;
            AppLog.e("periodAchieveConfirm:" + periodAchieveConfirm);
            if(periodAchieveConfirm == 0){
                changeForecastStart();
            }
            isAlgorithmUsed = true;
        }
        if(mensesHintValue == 0 && referMensesChoiceValue == 1 && mensesBlood == 0){
            AppLog.i("algorithm Menses deleteEnd");
            int result = algorithm.executeAL(5, algorithm.getMensesDayInput(recordDaySeconds, 5), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
            if(result == 234) g1Tog2Algorithm();
            isAlgorithmUsed = true;
        }

        AppLog.i("wzz-----isAlgorithmUsed------"+isAlgorithmUsed);
//        /**
//         * 温度算法有关
//         */
//        long currentDayCycleUnitDSMensesStartConfirm = dbManager.getSelectedDayCycleUnitDSMensesStartConfirm(App.userName, new Date().getTime()/1000);//（取今天的时间）当前周期的经期开始时间
//        AppLog.e("currentDayCycleUnitDSMensesStartConfirm:" + currentDayCycleUnitDSMensesStartConfirm);
//        long firstMensesStartConfirm = dbManager.getCycleUnitDSMensesFirstStartConfirm(App.userName);//整个算法数据中的第一个经期开始时间
//        AppLog.e("firstMensesStartConfirm:" + firstMensesStartConfirm);
//        if(currentDayCycleUnitDSMensesStartConfirm < recordDaySeconds ){
//            if ((selectedDayTemper.size() > 0) && (referBBT != selectedDayTemper.get(0).getTemperature())) {
//                AppLog.i("algorithm bbt");
//                int result = algorithm.executeAL(11, algorithm.getBBTDayInput(), algorithm.getBBTMucusCycleInput(), isSynced);
//                if(result == 234) g1Tog2Algorithm();
//                referBBT = selectedDayTemper.get(0).getTemperature();
//                isAlgorithmUsed = true;
//            }
//        }else{
//            if((firstMensesStartConfirm > 0 && recordDaySeconds >firstMensesStartConfirm)){
//
//            }if ((selectedDayTemper.size() > 0) && (referBBT != selectedDayTemper.get(0).getTemperature())) {
//                AppLog.i("algorithm bbt history");
//                int result = algorithm.executeAL(23, algorithm.getHistoryBBTDayInput(recordDaySeconds), algorithm.getHistoryBBTCycleInput(recordDaySeconds), isSynced);
//                if(result == 234) g1Tog2Algorithm();
//                referBBT = selectedDayTemper.get(0).getTemperature();
//                isAlgorithmUsed = true;
//            }
//        }

//        /**
//         * 宫颈粘液算法相关
//         */
//        if (mucusInfo != 0 && mucusInfo != referMucusInfo) {
//            AppLog.i("algorithm mucus");
//            int result = algorithm.executeAL(12, algorithm.getMucusDayInput(), algorithm.getBBTMucusCycleInput(), isSynced);
//            if(result == 234) g1Tog2Algorithm();
//            referMucusInfo = mucusInfo;
//            isAlgorithmUsed = true;
//        }

        /**
         * 调用算法后更新UI
         */
        if (isAlgorithmUsed) {
            isAlgorithmUsed = false;
            jsonArrayCycleDatas = algorithm.getCycleOutputJson();
            jsonArrayUserDatas = algorithm.getDayOutputJson();
            jsonObjectUserData = algorithm.getUserInfoJson();
            dbManager.initDayUnitDSOutputsList2Memory(App.userName);
            AlgoUpdateMsg algoUpdateMsg = new AlgoUpdateMsg();
            algoUpdateMsg.setRespCode(1);
            EventBus.getDefault().post(algoUpdateMsg);
            if (isSynced == 1)
                uploadCycleDatas();
            else {
                AppLog.e("msg at is not synced!");
                TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                temperUploadMsg.setUpdateCode(2);
                EventBus.getDefault().post(temperUploadMsg);
            }
        } else {
            AppLog.e("msg at is not isAlgorithmUsed!");
            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
            temperUploadMsg.setUpdateCode(2);
            EventBus.getDefault().post(temperUploadMsg);
        }

        MensesMsg mensesMsg = new MensesMsg();
        EventBus.getDefault().post(mensesMsg);
    }

    //算法返回值为234时调用一代转二代
    private void g1Tog2Algorithm(){
        UserUnitDS userData = new UserUnitDS();
        userData.averageMenstruationLength = App.memory_preference_mensesLen;
        userData.averageCycleLength = App.memory_preference_periodLen;
        DayUnitDSInput[] dayInput = dbManager.getDayInputListFromG1Record(App.userName);
        AppLog.i("wzz-----g1Tog2Algorithm------1");
        algorithm.g1FirstLoginG2(userData, dayInput, 0);
        AppLog.i("wzz-----g1Tog2Algorithm------2");
        checkIfNeedDealHistoryData();
    }

    private void checkIfNeedDealHistoryData() {
        CycleUnitDS[] cycleUnitDSes = dbManager.getALCycleOutput(App.userName, null);
        if(null != cycleUnitDSes && cycleUnitDSes.length > 0){
            for(int i = 0; i < cycleUnitDSes.length; i++){
                cycleUnitDSes[i].ovulationDayUserRecordBasis = -99;
            }
            dbManager.saveALCycleOutput(cycleUnitDSes, 0);
        }

        List<DayUnitDSOutput> dayUnitDSOutputs = dbManager.getALDayUnitDSOutputList(App.userName);
        if(null != dayUnitDSOutputs && dayUnitDSOutputs.size() > 0){
            for(int i = 0; i < dayUnitDSOutputs.size(); i++){
                dayUnitDSOutputs.get(i).periodAchieveForecast = 99;
            }
            dbManager.saveALDayOutput(dayUnitDSOutputs, 0);
        }
        saveALResult2Sqlite(0);
    }

    private void saveALResult2Sqlite(int isSynced) {
        algorithm.saveALData2Sqlite(isSynced);
    }

    private void changeForecastStart() {
        long zeroTime = DateUtil.getDateZeroTime2bit(new Date().getTime() / 1000) - 12 * 3600;
        int result = algorithm.executeAL(7, algorithm.getChangeForecastMensesStartDayInput(zeroTime), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), 0);
        if(result == 234) g1Tog2Algorithm();
    }

    private void uploadCycleDatas() {

        OKHttpUtil okHttpClient = new OKHttpUtil(context);
        String appendUrl = "cycle/replaceCycle.json";
        try {
            AppLog.i("cycleData = " + jsonArrayCycleDatas);
            AppLog.i("userData = " + jsonArrayUserDatas);
            AppLog.i("userInfo = " + jsonObjectUserData);
            okHttpClient.add("authToken", App.authToken);
            AppLog.i("authToken = " + App.authToken);
            if (null != jsonArrayCycleDatas)
                okHttpClient.add("cycleData", jsonArrayCycleDatas);
            if (null != jsonArrayUserDatas)
                okHttpClient.add("userData", jsonArrayUserDatas);
            if (null != jsonObjectUserData)
                okHttpClient.add("userInfo", jsonObjectUserData);
            if (null == jsonArrayCycleDatas && null == jsonObjectUserData && null == jsonArrayUserDatas)
                return;
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    algorithm.saveALData2Sqlite(0);
                    TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                    temperUploadMsg.setUpdateCode(2);
                    EventBus.getDefault().post(temperUploadMsg);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                    try {
                        String str = response.body().string();
                        AppLog.i("cycle/replaceCycle response:" + str);
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (200 == respCode) {
                            AppLog.i("UploadCycleData onResponse success!");
                            temperUploadMsg.setUpdateCode(2);
                            EventBus.getDefault().post(temperUploadMsg);
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            uploadCycleDatas();
                        } else {
                            algorithm.saveALData2Sqlite(0);
                            temperUploadMsg.setUpdateCode(2);
                            AppLog.i("UploadCycleData onResponse failed! respCode = " + respCode);
                            EventBus.getDefault().post(temperUploadMsg);
                        }
                    } catch (JSONException e) {
                        algorithm.saveALData2Sqlite(0);
                        e.printStackTrace();
                        temperUploadMsg.setUpdateCode(2);
                        EventBus.getDefault().post(temperUploadMsg);
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("UploadCycleData JSONException!");
            algorithm.saveALData2Sqlite(0);
            e.printStackTrace();
            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
            temperUploadMsg.setUpdateCode(2);
            EventBus.getDefault().post(temperUploadMsg);

        }
    }

}
